<?php

namespace app\v1\model;

use think\Model;

use think\Db;

/**
 * Class Integral
 * @package app\v1\model
 * 模块说明：这个类是用来处理积分模块的数据
 */
class Integral extends Base
{
    //
    //获取孩子的积分信息
    public function getChildIntegralInfo(){
       $userInfo=getUserInfo();
       $user=model('v1/User');
       $childInfo=$user->getCommonInfo($userInfo['childId'],$userInfo['orgId'],$userInfo['schoolId']);
       $picValueList=$this->getTypeIntegralList($userInfo['childId']);
       $integralInfo=$this->getIntegralInfo($userInfo['childId']);
       $rankingsList=$this->getMonthIntegralRankings($userInfo['schoolId']);
        $data=array('childInfo'=>$childInfo,'integralInfo'=>$integralInfo,'picValueList'=>$picValueList,'rankingsList'=>$rankingsList);
       renderData(0,'ok',$data);
    }

    //获取积分信息
    public function getIntegralInfo($childId){
        $map['iur.effect']=1;
        $map['iur.active']=1;
        $map['iur.user_id']=$childId;
        $totalIntegral=$this->getChildTotalIntegral($childId);
        $monthRankings=$this->getMonthRanking();
        $allTotalIntegral=$this->getChildAllTotalIntegral($map);
        $data=array('totalIntegral'=>$totalIntegral,'allTotalIntegral'=>$allTotalIntegral,'monthRankings'=>$monthRankings);
        return $data;
    }

    //获取孩子的月排行名次
    public function getMonthRanking(){
        $userInfo=getUserInfo();
        $map['iur.effect']=1;
        $map['iur.active']=1;
        $map['iur.shop_id']=$userInfo['schoolId'];
        $rankingsList=Db::name('Integral_user_relation')->alias('iur')->join('integral i','iur.integral_id=i.id','LEFT')->join('users u','iur.user_id=u.id')->join('integral_value v','i.integral=v.integral')->
        join('integral_gift ig','iur.integral_gift_id=ig.id','LEFT') ->join('student_infomation si','u.id=si.user_id','LEFT')->where($map)->field('(sum(v.value)-sum(ifnull(ig.value,0))) as totalIntegral,u.name,u.id as childId,u.headimgurl as avatar,si.school,si.grade,si.class')
            ->group('iur.user_id')->order('totalIntegral desc')->select();
        foreach($rankingsList as $key=>$value){
            if($value['childId']==$userInfo['childId']){
                return $key+1;
            }
        }
        return '-';

    }


    //获取某个孩子的积分
    public function getChildTotalIntegral($childId){
        $map['iur.effect']=1;
        $map['iur.active']=1;
        $map['iur.user_id']=$childId;
      $totalIntegral=$this->getChildAllTotalIntegral($map);
       $giftIntegral=Db::name('Integral_user_relation')->alias('iur')->join('integral_gift ig','iur.integral_gift_id=ig.id')->where($map)->sum('value');
       $totalIntegral=$totalIntegral-$giftIntegral;
        return $totalIntegral;
    }
    //获取某个孩子的累计积分
    public function getChildAllTotalIntegral($map){

        $totalIntegral=Db::name('Integral_user_relation')->alias('iur')->join('integral i','iur.integral_id=i.id')->join('integral_value v','i.integral=v.integral')->where($map)->sum('v.value');
//        dump($totalIntegral);
//        die;
        return $totalIntegral;
    }

    //获取本月校区积分前十名0:固定值，1：获取分页
    public function getMonthIntegralRankings($schoolId,$type=0){
        if($type==1){
            $count=$this->pageCount;
        }else{
            $count=5;
        }
        $map['iur.effect']=1;
        $map['iur.active']=1;
        $map['iur.shop_id']=$schoolId;
        $rankingsList=Db::name('Integral_user_relation')->alias('iur')->join('integral i','iur.integral_id=i.id','LEFT')->join('users u','iur.user_id=u.id')->join('integral_value v','i.integral=v.integral','LEFT')->
        join('integral_gift ig','iur.integral_gift_id=ig.id','LEFT') ->join('student_infomation si','u.id=si.user_id','LEFT')->where($map)->field('(sum(v.value)-sum(ifnull(ig.value,0))) as totalIntegral,u.name,u.headimgurl as avatar,si.school,si.grade,si.class')
           ->group('iur.user_id')->order('totalIntegral desc')->limit($count)->page($this->currentPage)->select();
        return $rankingsList;
    }

    //获取学校学生的积分排名
    public function getAllMonthIntegralRankings(){
        $userInfo=getUserInfo();
        $rankingsList=$this->getMonthIntegralRankings($userInfo['schoolId'],1);
        $data=array('current_page'=>$this->currentPage,'rankingsList'=>$rankingsList);
        renderData(0,'ok',$data);
    }

    //获取学生的5个类型页信息
    public function getCommentIntegralInfo(){
        $userInfo=getUserInfo();
        $user=model('v1/User');
        $result=$user->getCommonInfo($userInfo['childId'],$userInfo['orgId'],$userInfo['schoolId']);
       $theList=$this->getTypeIntegralList($userInfo['childId']);
        $imap['iur.effect']=1;
        $imap['iur.active']=1;
        $imap['iur.user_id']=$userInfo['childId'];
        $totalIntegral=$this->getChildAllTotalIntegral($imap);
        $data=array('childName'=>$result['name'],'avatar'=>$result['avatar'],'totalIntegral'=>$totalIntegral,'list'=>$theList);
        renderData(0,'ok',$data);

    }

    //获取行为习惯5个分数列表
    public function getTypeIntegralList($childId){
        $map['i.effect']=1;
        $map['i.active']=1;
        $map['iur.user_id']=$childId;
        $list=Db::name('Integral')->alias('i')->join('integral_user_relation iur','i.id=iur.integral_id')->join('integral_value iv','i.integral=iv.integral')->where($map)->group('i.type')->field('i.type,sum(iv.value) as integral')->select();
//       dump($list);
//       die;
        $theList=array();
        for($i=1;$i<=5;$i++){
            if(!empty($list)) {
                foreach ($list as $key => $value) {
                    if ($i == $value['type']) {
                        $theList[] = $value;
                    }
                    if(sizeof($list)==$key+1&&empty($theList[$i-1])){
                        $theList[] = array('type' => $i, 'integral' => 0);
                    }
                }
            }else{
                $theList[] = array('type' => $i, 'integral' => 0);
            }
        }
        return $theList;
    }


    //积分历史页
    public function getIntegralHistoryPage(){
        $userInfo=getUserInfo();
        $user=model('v1/User');
        $childInfo=$user->getCommonInfo($userInfo['childId'],$userInfo['orgId'],$userInfo['schoolId']);
        $integralInfo=$this->getIntegralInfo($userInfo['childId']);
        $integralList=$this->getChildHistoryIntegral($userInfo['childId']);
        $data=array('childInfo'=>$childInfo,'integralInfo'=>$integralInfo,'integralList'=>$integralList);
        renderData(0,'ok',$data);

    }


    //获取孩子的历史积分记录
    public function getChildHistoryIntegral($childId){
        $map['iur.user_id']=$childId;
        $map['iur.effect']=1;
        $map['iur.active']=1;
        $integralList=Db::name('integral_user_relation')->alias('iur')->join('integral i','i.id=iur.integral_id','LEFT')->join('integral_value iv','i.integral=iv.integral','LEFT')
            ->join('integral_gift ig','iur.integral_gift_id=ig.id','LEFT')->where($map)->limit($this->pageCount)
           ->page($this->currentPage)->field('type,(iv.value) as integral,iur.append_time as appendTime,ig.name as giftName,ig.pic as giftPic,ig.value as giftValue')->order('iur.id desc')->select();

        $data=array('current_page'=>$this->currentPage,'list'=>$integralList);
        return $data;
    }

    //积分商品页
    public function integralGiftPage(){
        $userInfo=getUserInfo();
        $user=model('v1/User');
        $childInfo=$user->getCommonInfo($userInfo['childId'],$userInfo['orgId'],$userInfo['schoolId']);
        $integralInfo=$this->getIntegralInfo($userInfo['childId']);
        $giftList=$this->getSchoolGiftList($userInfo['schoolId'],$integralInfo['totalIntegral']);
        $data=array('childInfo'=>$childInfo,'integralInfo'=>$integralInfo,'giftList'=>$giftList);
        renderData(0,'ok',$data);
    }

    //获取学校的积分商品列表
    public function getSchoolGiftList($schoolId,$totalIntegral){
        $map['shop_id']=$schoolId;
        $map['effect']=1;
        $map['active']=1;
        $giftList=Db::name('Integral_gift')->where($map)->limit($this->pageCount)->page($this->currentPage)->field('id as giftId,pic as giftPic,name as giftName,value as giftIntegral,count')->select();
        foreach($giftList as $key=>$value){

            if($value['giftIntegral']>$totalIntegral){
                $giftList[$key]['status']=-1;

            }else if($value['count']==0){
                $giftList[$key]['status']=-2;
            }else{
                $giftList[$key]['status']=1;
            }

        }
        $data=array('current_page'=>$this->currentPage,'list'=>$giftList);
        return $data;
    }
    //积分兑换
    public function commitExchange($giftId){
        $userInfo=getUserInfo();
        $totalIntegral=$this->getChildTotalIntegral($userInfo['childId']);
        $this->checkGiftIntegral($giftId,$totalIntegral);
        Db::startTrans();
        try{
            $data['append_user_id']=$userInfo['parentId'];
            $data['append_time']=time();
            $data['modify_user_id']=$userInfo['parentId'];
            $data['modify_time']=time();
            $data['effect']=1;
            $data['active']=1;
            $data['org_id']=$userInfo['orgId'];
            $data['shop_id']=$userInfo['schoolId'];
            $data['user_id']=$userInfo['childId'];
            $data['integral_gift_id']=$giftId;
            $res=Db::name('Integral_user_relation')->insert($data);
            $map['id']=$giftId;

            $res2=Db::name('Integral_gift')->where($map)->setDec('count');
            // 提交事务
            Db::commit();
            renderInfo(0,'兑换成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            renderInfo(400001,'系统繁忙,请稍后重试');
        }
    }

    //检查礼物所需的积分和孩子的积分比较是否足够
    public function checkGiftIntegral($giftId,$totalIntegral){
            $map['id']=$giftId;
            $map['effect']=1;
            $map['active']=1;
            $giftInfo=Db::name('Integral_gift')->where($map)->find();
            if(empty($giftInfo)){
               renderInfo(400001,'该商品已经下架');
            }
            //库存判断
            if($giftInfo['count']==0){
                renderInfo(400001,'该商品库存不足');
            }
            //所需积分值
            $giftValue=(int)$giftInfo['value'];
            if($totalIntegral<$giftValue){
                renderInfo(400001,'您的积分不足无法兑换');
            }


    }




}
